package ws

import (
	"sync"
)

type socketPool struct {
	connections map[int64]*SocketSingleton
	lock        sync.Mutex
}

var SocketPoolInstance = &socketPool{
	connections: make(map[int64]*SocketSingleton),
}

func (sp *socketPool) getConnection(id int64) *SocketSingleton {
	return sp.connections[id]
}

func (sp *socketPool) addConnection(id int64, socket *SocketSingleton) {
	sp.lock.Lock()
	defer sp.lock.Unlock()
	sp.connections[id] = socket
}

func (sp *socketPool) removeConnection(id int64) {
	sp.lock.Lock()
	defer sp.lock.Unlock()
	if sp.connections[id] != nil {
		delete(sp.connections, id)
	}
}

func (sp *socketPool) Broadcast(message string) {
	sp.lock.Lock()
	defer sp.lock.Unlock()
	for _, s := range sp.connections {
		s.SendString(message)
	}
}

func (sp *socketPool) CloseAll() {
	sp.lock.Lock()
	defer sp.lock.Unlock()
	for id, s := range sp.connections {
		s.Close()
		delete(sp.connections, id)
	}
	sp.connections = nil
}

func (sp *socketPool) GetOnlineCount() int {
	return len(sp.connections)
}
